public class homeWork2 {
//    (1) 有2个用户分别从同一个卡上取钱 (总额: 10000)
//    (2)每次都取1000,当余额不足时，就不能取款了
//    (3) 不能出现超取现象 =》 线程同步问题
    public static void main(String[] args) {

        BankCard bankcard=new BankCard();
        User user1=new User(bankcard,"用户一");
        User user2=new User(bankcard,"用户二");
        Thread a1=new Thread(user1);
        Thread a2=new Thread(user2);

        a1.start();
        a2.start();
        while (true){
            if (bankcard.checkMoney()<1000){
                Thread.yield();
            }
        }




    }

    static class User implements Runnable{
        BankCard bankcard;
        private boolean flag=true;
        String name;


        public User(BankCard bankcard,String name){
            this.bankcard=bankcard;
            this.name=name;
        }
        public void getMoney(){
            bankcard.pushMoney();
        }

        @Override
        public void run() {
            while (flag){
                synchronized (bankcard){
                    if (bankcard.checkMoney()<1000){
                        System.out.println("取钱失败,钱不够了");
                        System.out.println(bankcard.checkMoney());
                        flag=false;
                    }else {
                        this.getMoney();
                        System.out.println(this.name+"成功取出1000块");
                        System.out.println("卡里剩余"+bankcard.checkMoney());
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }
    }

    static class BankCard{
        private static int money=10000;

        public int checkMoney() {
            return money;
        }

        public void pushMoney(){
            this.money=this.money-1000;
        }

    }


}
